<?php

 /**
  * @package JooS
  * @subpackage Syntax
  */

  require_once "JooS/Syntax/Complex.php";

  final class JooS_Syntax_Complex_Repetition extends JooS_Syntax_Complex {
    private $maxCount = 0, $minCount = 0;

    /**
     * @param int $num
     * @return JooS_Syntax_Abstract
     */
    public function getRule($num = null) {
      return parent::getRule(null);
    }

    /**
     * @param int $maxCount
     */
    protected function setMaxCount($maxCount) {
      $this->maxCount = (int)$maxCount;
    }

    /**
     * @param int $minCount
     */
    protected function setMinCount($minCount) {
      $this->minCount = (int)$minCount;
    }
    
    public function init() {
      $args = func_get_args();

      parent::init(isset($args[0]) ? $args[0] : null);

      if (isset($args[1]) && !is_null($args[1]))
        $this->setMaxCount($args[1]);
      if (isset($args[2]) && !is_null($args[2]))
        $this->setMinCount($args[2]);
    }

    /**
     * @return string
     */
    public function compile() {
      $rule = $this->getRule();
      $cnt = 0;
      $compiledExpr = "";

      $min = $this->minCount;
      $max = $this->maxCount;

      while (true) {
        $newCompiledExpr = $rule->compileSyntax();
        if ($newCompiledExpr === false) {
          if ($cnt < $min) {
            $compiledExpr = false;
          }
          break;
        }

        $compiledExpr .= $newCompiledExpr;
        $cnt++;

        if ($cnt == $max) {
          break;
        }
      }
      return $compiledExpr;
    }
  }
